package com.template.controller;

import com.template.common.base.BaseController;
import com.template.common.exception.BusinessException;
import com.template.common.result.Result;
import com.template.common.result.ResultCode;
import com.template.entity.User;
import com.template.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 用户控制器
 * 
 * @author template
 * @since 2024-01-01
 */
@RestController
@RequestMapping("/user")
public class UserController extends BaseController<User, UserService> {

    @Autowired
    private UserService userService;

    @GetMapping("/username/{username}")
    public Result<User> getByUsername(@PathVariable String username) {
        User user = userService.getByUsername(username);
        if (user == null) {
            return Result.error(ResultCode.DATA_NOT_EXIST);
        }
        return Result.success(user);
    }

    @GetMapping("/email/{email}")
    public Result<User> getByEmail(@PathVariable String email) {
        User user = userService.getByEmail(email);
        if (user == null) {
            return Result.error(ResultCode.DATA_NOT_EXIST);
        }
        return Result.success(user);
    }

    @PostMapping("/check/username")
    public Result<Boolean> checkUsername(@RequestParam String username) {
        boolean exists = userService.existsByUsername(username);
        return Result.success(exists);
    }

    @PostMapping("/check/email")
    public Result<Boolean> checkEmail(@RequestParam String email) {
        boolean exists = userService.existsByEmail(email);
        return Result.success(exists);
    }

    @PostMapping("/register")
    public Result<Boolean> register(@Valid @RequestBody User user) {
        // 检查用户名是否已存在
        if (userService.existsByUsername(user.getUsername())) {
            throw new BusinessException("用户名已存在");
        }
        
        // 检查邮箱是否已存在
        if (user.getEmail() != null && userService.existsByEmail(user.getEmail())) {
            throw new BusinessException("邮箱已存在");
        }
        
        // 设置默认状态
        if (user.getStatus() == null) {
            user.setStatus(1);
        }
        
        boolean result = userService.save(user);
        return result ? Result.success("注册成功", null) : Result.error("注册失败");
    }

    @PutMapping("/update")
    public Result<Boolean> updateUser(@Valid @RequestBody User user) {
        if (user.getId() == null) {
            throw new BusinessException("用户ID不能为空");
        }
        
        // 检查用户是否存在
        User existUser = userService.getById(user.getId());
        if (existUser == null) {
            throw new BusinessException(ResultCode.DATA_NOT_EXIST);
        }
        
        // 如果更新用户名，检查是否重复
        if (user.getUsername() != null && !user.getUsername().equals(existUser.getUsername())) {
            if (userService.existsByUsername(user.getUsername())) {
                throw new BusinessException("用户名已存在");
            }
        }
        
        // 如果更新邮箱，检查是否重复
        if (user.getEmail() != null && !user.getEmail().equals(existUser.getEmail())) {
            if (userService.existsByEmail(user.getEmail())) {
                throw new BusinessException("邮箱已存在");
            }
        }
        
        boolean result = userService.updateById(user);
        return result ? Result.success("更新成功", null) : Result.error("更新失败");
    }

    @GetMapping("/status/{status}")
    public Result<List<User>> listByStatus(@PathVariable Integer status) {
        List<User> users = userService.lambdaQuery()
                .eq(User::getStatus, status)
                .list();
        return Result.success(users);
    }
}
